#include <unistd.h>
#include <iostream>
#include <stdlib.h>

int main()
{
  //pipe file
  int pipefd[2]={};

  if(pipe(pipefd) < 0){
    //error
    std::cerr << "create pipe fail" << std::endl;
  }

  int pid = fork();
  if(pid < 0){
    //error
    std::cerr << "fork fail" << std::endl;
  }//if
  else if(pid == 0){
    //child for read so close write
    close(pipefd[1]);

    while(true){
      int buf = 0;
      ssize_t s = read(pipefd[0], &buf, sizeof(int));
      
      if(s < 0){
        //error or read end
        std::cerr << "read fail" << std::endl;
        break;
      }
      else if(s ==  0){
        std::cout << "child end" << std::endl;
        break;
      }
      else{
        //read success
        std::cout << "read: " << buf << std::endl;
        sleep(2);
      }//else
    }//while

    close(pipefd[0]);
    exit(0);
  }//else if
  else{

    //parent for write so close read 
    close(pipefd[0]);

    int cnt = 0;
    while(cnt <= 10){
      //std::cout << "just wrtie a number and 0 for quit: ";
      //std::cin >> buf;
      int buf = cnt++;
      //if(buf == 10) break;//quit 
      ssize_t s = write(pipefd[1], &buf, sizeof(buf));
      if(s < 0){
        //write error
        std::cerr << "write fail" << std::endl;
        break;
      }

      sleep(2);
    }//while
    close(pipefd[1]);
    std::cout << "parent end" <<  std::endl;
  }//else

}//main
